#!/usr/bin/env perl

use lib qw{../config ../lib/perl};
use strict;
use warnings;
use CGI;
use LWP::UserAgent;
use Util;
use TRFLP;

my $cgi = new CGI;
my $dir = $cgi->param('dir');

Util::open_cgi_shell("Copying files from remote directory");

print "<b>&gt; listing remote directory $dir ...</b>";

#my @files = Util::list_remote("$TRFLP::site_url/$dir");
my @files = Util::list_remote_dir("$dir");
print qq( <font color="#00D000">OK</font>\n);

# copy files
unless ( -d "$TRFLP::data_path/$dir" ) {
  Util::run_task(*STDOUT, "mkdir $TRFLP::data_path/$dir");
}

Util::run_task(*STDOUT, qq(echo "<b>&gt; fetching files ...</b>"), "silent");

my $ua = Net::FTP->new($TRFLP::dnacore_server, Passive => 1, Debug => 0)
  or die "ERROR: Cannot connect to $TRFLP::dnacore_server: $@";

$ua->login($TRFLP::dnacore_user, $TRFLP::dnacore_password)
  or die "ERROR: Cannot login to $TRFLP::dnacore_server: " . $ua->message;

$ua->cwd("$TRFLP::dnacore_dir/$dir")
  or die "ERROR: Cannot chdir to $TRFLP::dnacore_dir/$dir: " . $ua->message;

my $n = @files;
my $i = 1;
foreach ( @files ) {
  print STDERR "fetching: $_->[1]\n";
  my ( $mtime, $file ) = @$_;

  my $name = $file;
  $name =~ s/.fsa$//i;

  my $local_file;
  my $retry = 3;
  while ( $retry ) {
    $local_file = $ua->get($file)
      or do {
	print qq(\t<span style="color: #D00">$file</span>: failed to get; trying again ... <span>\n);
	$retry--;
	next;
      };
    last;
  }

  $file =~ s/FSA$/fsa/;
  my $content = `cat $local_file`;
  system("mv $local_file $TRFLP::data_path/$dir/$file") == 0 or die $!;
  my ($sample, $standard) = Util::parse_abif($content);
  open DATA, ">$TRFLP::data_path/$dir/$name.sample" or die $!;
  print DATA join("\n", @$sample, '');
  close DATA;
  open DATA, ">$TRFLP::data_path/$dir/$name.standard" or die $!;
  print DATA join("\n", @$standard, '');
  close DATA;
  print qq(\t$i/$n\t<span style="color: #0D0">$file</span>\n);
  $i++;
}

Util::close_cgi_shell();
